<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/


jimport( 'joomla.application.component.model' );

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JobBoardModelJAPayment extends JModel
{        		
	var $_table_credits_invoice = null;
	var $_table_trans = null;
	
	function getPackage($table_name, $id){
	
		$db = JFactory::getDBO();
		$sql = "select * from #__$table_name where published=1 and id=".(int)$id;
		$db->setQuery($sql);
		return $db->loadObject();
	
	}
	
    function add_waiting_payment($status=0, $currency='USD', $payment_method, $product_type, $product){
		global $jbconfig;				
		
		$db = JFactory::getDBO();
		
    	$data = JRequest::get('post');
    	$id = JRequest::getInt('cid', 0);
    	
    	$user = JFactory::getUser();    			
		
		$data = $this->getTable_transactions();		
	    $data->created_date = date("Y-m-d H:i:s");	    
	    $data->completed = $status;
	    $data->user_id = $user->id;
	    $data->product_id = $product->id;
	    $data->product_type = $product_type;
	    $data->value = $product->value;	   
	    $data->value_type = isset($product->type)?$product->type:'';
	    
	    // Check TAX
	    $tax = $this->checkTAX($product);
	    $taxmsg = "";
	    if($tax)
	    	$taxmsg = "<br/>TAX rate: ".$tax->tax_rate."%";
	    	     
	    $data->amount = $product->price;
	    $data->payment_method = $payment_method;
	    $data->currency_code = $currency;
	    $data->ip = $_SERVER['REMOTE_ADDR'];
	    $data->detail = JText::_("Pay for "). $product->title.": #".$product->id.$taxmsg;
	    
	    // Check coupon system
		if( JRequest::getVar("coupon_code", "") != ""){
		    $coupon_code = JRequest::getVar("coupon_code", "");
		    $result = $this->checkCouponCode($coupon_code, $product);
		    if( $result !== false ){
		        $data->amount         = $data->amount - $result->discount_amount;
		        $data->detail = "Employer using Coupon code: ".$coupon_code."<br/>".$data->detail;
		        
		        // Update log data
		        $sql = "SELECT * FROM #__ja_coupon_code WHERE code = '".$coupon_code."'";
		        $db->setQuery($sql);
		        $result = $db->loadObject();
		        $userid = "u".$user->id;
		        $log = new stdClass();
		        if( isset($result->log) && $result->log != ""){		            
		            $log = unserialize($result->log);
		            if( isset( $log->{$userid} ) )
		              $log->{$userid}++;
		            else $log->{$userid} = 1;
		        }else $log->{$userid} = 1;
		        
		        $log = serialize($log);
		        $sql = "UPDATE #__ja_coupon_code SET `log` = '".$log."' , `used` = `used` + 1 WHERE id = ".$result->id;
		        $db->setQuery($sql);		        
		        $db->query();		        
		    }
		}
	    
	    if($data->store()){
	    	/* Send mail to employer */	
	    	if ($jbconfig['emails']->get('enabled'))
	    	{
	    		$this->email_posting_order_wait('email_posting_plan_wait', $data, $data->product_id, $product_type);
	    		if ($jbconfig['emails']->get('fromemail'))
	    			$this->admin_email_posting_order_wait('AdminMailNewOrder', $data, $data->product_id, $product_type, $user->id);
	    	}
	    	
			return $data;
		} else{
			JError::raiseNotice(40001, JText::_("Errors occur during the create invoice"));
			return false;
		}
		return false;		
	}
	
		
	function payment_error() {
   		JError::raiseNotice(1, JText::_("Sorry we can not find information about your transaction. Please contact Administrator For more information."));
   	}
   	
   	function update_transaction($row) {
   		$db = JFactory::getDBO();
   		$db->updateObject("#__ja_transactions", $row, 'id');
   	}
   	
   	function pending_payment($result){
   		global $jbconfig;   		   		
		
		/* Update Transaction Table */
   		$this->update_transaction($result);
		/* Send mail to employer */	
		if ($jbconfig['emails']->get('enabled')){						
			$this->email_posting_order_pending($result, 'email_posting_plan_pending', $result->datas['custom'], $result->product_type);
		}
   		
   	}
   	
   	function complete_payment($result){
   		global $jbconfig;
   		
   		$user = getUser($result->user_id);   		   		   		
		
		/* Update account for user: Update credit_balance field */
		$account = getAccountByUserID($user->id);
		$payment_sys_title = '';
		$payment_sys = get_payment_gateways($result->payment_method);
		if($payment_sys) $payment_sys_title = $payment_sys[0]->alias;
		$vars = new stdClass();
		
		switch ($result->product_type){
			case 'P':{				
				$detail 	= JText::_("POSTING PLAN FOR USER ID").": #".$result->user_id." ( ".$payment_sys_title." ".JText::_("Payment ID: #").$result->id.")";
				$template = 'email_posting_plan_completed';
				
				$product = $this->getPackage('ja_posting_plans', $result->product_id);
				if(!$product){
					JError::raiseError(JText::_('This Product ID:').$result->product_id. JText::_(' not found'));
					return false;
				}
				if($product->type=='standard')	    $vars->standard_posts_balance = $product->value + (int)$account->standard_posts_balance;
			    if($product->type=='premium')		$vars->premium_posts_balance = $product->value + (int)$account->premium_posts_balance;
		
			    if($product->type=='resume'){
			    	$end_date = $account->end_date_search_resume;
			    	if($end_date!=''){
				    	$end_date = getdate(strtotime($end_date));
				    	$time_end_date = $end_date[0];
				    	if(time()<$time_end_date){
				    		$vars->end_date_search_resume = date('Y-m-d H:i:s', mktime($end_date['hours'], $end_date['minutes'], $end_date['seconds'], $end_date['mon'], $end_date['mday']+$product->value, $end_date['year']));
				    	}
				    	else{
				    		$vars->begin_date_search_resume = date('Y-m-d H:i:s');
				    		$vars->end_date_search_resume   = date('Y-m-d H:i:s', mktime(date('H'), date('i'), date('s'), date('m'), date('d')+$product->value,date('Y')));
				    	}
			    	}
			    }
				
			}break;
				
			case 'C':
				$product = $this->getPackage('ja_credits', $result->product_id);
				$detail 	= JText::_("CREDIT FOR USER ID").": #".$result->user_id." ( ".$payment_sys_title." ".JText::_("Payment ID: #").$result->id.")";		
				$vars->credit_balance = (int)$result->value + (int)$account->credit_balance;
				$template = 'email_credit_completed';
				break;
				
			case 'S':
				$table_name = 'ja_subscriptions_invoice';
				$template = 'email_subscription_completed';
				break;
		}						
		$vars->user_id = $user->id;		
		
		$makeok = update_account_for_employer($vars);	
		
		$this->update_transaction($result);
		if ($jbconfig['emails']->get('enabled'))	
		{			
			$this->email_posting_order_completed($result, $product->id, $template, $result->product_type);
			if ($jbconfig['emails']->get('enabled')){	
				/* Send mail to admin */
				$this->admin_email_posting_order_completed($result, $product->id, 'adminmailcompletedorder', $result->product_type);

				/* Send mail to employer */
				$this->email_posting_order_completed($result, $product, 'email_posting_plan_completed', $result->product_type);
			}
			
		}
		
		/* Update Transaction Table */   		
		return $makeok;
   	}	
	
   	
   	function getTable_plan_invoice(){
		 if($this->_table_invoice == null){
        	$this->_table_invoice = &JTable::getInstance('JA_PostingPlans_invoice', 'JobBoardTable');
		}
		return $this->_table_invoice;
	}

	function getTable_transactions(){
		 if($this->_table_trans == null){
        	$this->_table_trans = &JTable::getInstance('JA_Transactions', 'JobBoardTable');
		}
		return $this->_table_trans;
	}
	
	/* Send mail when employer completed the payment*/
	function email_posting_order_completed($invoice, $product, $template='email_posting_plan_completed', $prefix='P'){
		global $jbconfig;
		
		/* send notice email to the user and Cc to admin */
		if(!$invoice) return false;
		if(!$jbconfig['emails']->get('enabled')){
			return true;
		}
				
		$user = JFactory::getUser($invoice->user_id);
		$profile = getProfileFromUserId($invoice->user_id);
		
		$arr_link = array();
		$arr_link['ja_transactions'] = $invoice->id;
		$arr_link['users'] = $invoice->user_id;
		$arr_link['ja_profiles'] = $profile->id;
		switch (strtolower($prefix))
		{
			case 'p':
				$table_name = 'ja_posting_plans';
				break;
			case 's':
				$table_name = 'ja_subscriptions';
				break;
			case 'c':
				$table_name = 'ja_credits';
				break;
			default:
				$table_name = 'ja_posting_plans';
				break;
		}
		
		$payment_method = get_payment_gateways( $invoice->payment_method );
		$payment_method = $payment_method[0];
		$objemail = null;
		if($payment_method->custom_payment_completed_mail){
			if(!$objemail = exists_EmailTemplate('send_payment_completed_mail', $product, $invoice->payment_method )){
				$objemail = exists_EmailTemplate($template, $product, $invoice->payment_method );
			}			
		}
		if (!$objemail)
			$objemail = $template;
			
		$mail = get_EmailTemplate($arr_link, $objemail);
		if($mail){
    		if (!$mail->EmailFromAddress) 
    			$mail->EmailFromAddress = $emailConfig['fromemail'];
    		if (!$mail->EmailFromName) 
    			$mail->EmailFromName = $emailConfig['fromname'];			
			sendmail($user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName);
			return true;
		}
	}
	
	/* need to send mail */
	/* Send mail when employer complete the payment but the status of your transaction is pending*/
	function email_posting_order_pending($invoice,$template='email_posting_plan_pending', $product_id, $prefix='P', $user_id=null){
		
		global $jbconfig;
		$user = JFactory::getUser($user_id);
		$arr_link = array();
		$arr_link['ja_transactions'] = $invoice->id;
		$arr_link['users'] = $invoice->user_id;
		
		$profile = getProfileFromUserId($invoice->user_id);
		$arr_link['ja_profiles'] = $profile->id;
		
		switch (strtolower($prefix))
		{
			case 'p':
				$table_name = 'ja_posting_plans';
				break;
			case 's':
				$table_name = 'ja_subscriptions';
				break;
			case 'c':
				$table_name = 'ja_credits';
				break;
			default:
				$table_name = 'ja_posting_plans';
				break;
		}
		$arr_link[$table_name] = $product_id;
				
		$objemail = exists_EmailTemplate($template, $product_id, $invoice->payment_method );
		$mail = get_EmailTemplate($arr_link, $objemail);
		if($mail){
    		if (!$mail->EmailFromAddress) 
    			$mail->EmailFromAddress = $emailConfig['fromemail'];
    		if (!$mail->EmailFromName) 
    			$mail->EmailFromName = $emailConfig['fromname'];			
			sendmail($user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName);
			
			return true;
		}		
	}
	
	/* need to send mail */
	/* Send mail when employer order, the status of transaction is waited*/
	function email_posting_order_wait($template='email_posting_plan_wait', $invoice, $product_id, $prefix='P', $user_id=null){
		
		global $jbconfig;
		$user = JFactory::getUser($user_id);
		$arr_link = array();
		$arr_link['ja_transactions'] = $invoice->id;
		$arr_link['users'] = $invoice->user_id;
		
		switch (strtolower($prefix))
		{
			case 'p':
				$table_name = 'ja_posting_plans';
				break;
			case 's':
				$table_name = 'ja_subscriptions';
				break;
			case 'c':
				$table_name = 'ja_credits';
				break;
			default:
				$table_name = 'ja_posting_plans';
				break;
		}
		$arr_link[$table_name] = $product_id;
		
		$payment_method = get_payment_gateways( $invoice->payment_method );
		$payment_method = $payment_method[0];
		
		$objemail = null;
		if($payment_method->custom_payment_pending_mail){
			if(!$objemail = exists_EmailTemplate('send_payment_pending_mail', $product_id, $invoice->payment_method )){
				$objemail = exists_EmailTemplate($template, $product_id, $invoice->payment_method );
				$include_message = '';
			}			
			else 
			{
				if ($payment_method->name=='wirebank')
				{
					$PATH = JPATH_COMPONENT.DS."asset".DS."payments".DS.$payment_method->name.".php";
					require_once($PATH);
					$payment = new $payment_method->name($payment_method);
					JRequest::setVar('transaction_id',$invoice->id);
					$include_message = $payment->replace_param(JFilterInput::_decode($payment_method->wirebank_information));
				}
				else 	
					$include_message = '';
			}
		}
		if (!$objemail)
		{
			$objemail = $template;
			$include_message = '';
		}
		$mail = get_EmailTemplate($arr_link, $objemail,$include_message);
		if($mail){
    		if (!$mail->EmailFromAddress) 
    			$mail->EmailFromAddress = $emailConfig['fromemail'];
    		if (!$mail->EmailFromName) 
    			$mail->EmailFromName = $emailConfig['fromname'];		
			sendmail($user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName);
			return true;
		}		
		
	}
	
	/* need to send mail */
	/* Send mail when employer order, the status of transaction is waited*/
	function admin_email_posting_order_wait($template='AdminMailNewOrder', $invoice, $product_id, $prefix='P', $user_id=null){
		//Get Datas from transaction, bang employer, user, product tables
		global $jbconfig;
		
		$admin_email = $jbconfig['emails']->get('fromemail');
		$admin_name = $jbconfig['emails']->get('fromname')?$jbconfig['emails']->get('fromname'):'JA Jobboard administrator';
		
		$user = JFactory::getUser($user_id);
		$arr_link = array();
		$arr_link['ja_transactions'] = $invoice->id;
		$arr_link['users'] = $invoice->user_id;
		
		$profile = getCustomerProfile($invoice->user_id);
		
		$arr_link['ja_profiles'] = $profile->id;
		
		switch (strtolower($prefix))
		{
			case 'p':
				$table_name = 'ja_posting_plans';
				break;
			case 's':
				$table_name = 'ja_subscriptions';
				break;
			case 'c':
				$table_name = 'ja_credits';
				break;
			default:
				$table_name = 'ja_posting_plans';
				break;
		}
		$arr_link[$table_name] = $product_id;
		
		$mail = get_EmailTemplate($arr_link, $template);
		
		if($mail){
    		if (!$mail->EmailFromAddress) 
    			$mail->EmailFromAddress = $emailConfig['fromemail'];
    		if (!$mail->EmailFromName) 
    			$mail->EmailFromName = $emailConfig['fromname'];			
			sendmail($admin_email, $admin_name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName);
			return true;
		}		
		
	}
	
	function admin_email_posting_order_completed($invoice, $product, $template='email_posting_plan_completed', $prefix='P'){
		global $jbconfig;
		
		/* send notice email to the user and Cc to admin */
		if(!$invoice) return false;
		if(!$jbconfig['emails']->get('enabled')){
			return true;
		}
		
		$admin_email = $jbconfig['emails']->get('fromemail');
		$admin_name = $jbconfig['emails']->get('fromname')?$jbconfig['emails']->get('fromname'):'JA Jobboard administrator';		
		/* need to send mail */		
		
		$user = JFactory::getUser($invoice->user_id);
		$profile = getProfileFromUserId($invoice->user_id);
		$arr_link = array();
		$arr_link['ja_transactions'] = $invoice->id;
		$arr_link['users'] = $invoice->user_id;
		$arr_link['ja_profiles'] = $profile->id;
		switch (strtolower($prefix))
		{
			case 'p':
				$table_name = 'ja_posting_plans';
				break;
			case 's':
				$table_name = 'ja_subscriptions';
				break;
			case 'c':
				$table_name = 'ja_credits';
				break;
			default:
				$table_name = 'ja_posting_plans';
				break;
		}
		$arr_link[$table_name] = $product;
		$mail = get_EmailTemplate($arr_link, $template);
		if($mail){
    		if (!$mail->EmailFromAddress) 
    			$mail->EmailFromAddress = $emailConfig['fromemail'];
    		if (!$mail->EmailFromName) 
    			$mail->EmailFromName = $emailConfig['fromname'];			
			sendmail($admin_email, $admin_name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName);
			return true;
		}
	}	
	
	// Check coupon code
	// $code: Coupon code
	// $item: Credit item
	function checkCouponCode($code, $item){
	    $db =& JFactory::getDBO();
        
	    // Check code exist...
	    $db->setQuery("SELECT * FROM #__ja_coupon_code WHERE code = '".mysql_real_escape_string($code)."' LIMIT 1");
	    $result = $db->loadObject();	    
	    if( ! $result ){
	        JError::raiseWarning(1, JText::_("Your code doesn't exist on our system"));
	        return false;
	    }
	    
	    // Check used
	    if( $result->used > $result->count && $result->used < 99999 ){
	        JError::raiseWarning(1, JText::_("The used code is greater than its limit"));
	        return false;
	    }
	    
	    // Check Coupon Info
	    $db->setQuery("SELECT * FROM #__ja_coupon WHERE id = ".$result->coupon_id);
	    $resultCoupon = $db->loadObject();
	    
	    if( $resultCoupon ){
	        // Check publish
	        if( ! $resultCoupon->published ){
	           JError::raiseWarning(1, JText::_("Your code is unable to use"));
	           return false;
	        }
	        
	        // Check limit date
	        if( $resultCoupon->limit_date ){
	           if( ! (strtotime($resultCoupon->begin_date ) < time() && time() < strtotime($resultCoupon->end_date )) ){
	               JError::raiseWarning(1, JText::_("Your code is expired time to use"));
	               return false;
	           }
	        }
	        
	        // Check available for this Posting plan
	        if( !empty($resultCoupon->posting_plan) ){
	           $postingPlan = explode(",", $resultCoupon->posting_plan);
	           if( ! in_array(JRequest::getVar("ppid", "0"), $postingPlan) ){
	               JError::raiseWarning(1, JText::_("Your code is not apply for this Posting Plan/ Credit Order"));
	               return false;
	           }
	        }
	        
	        // Check number of use
	        if( !empty($result->log) && $resultCoupon->member_coupon_usage_count < 99999){
	            $log = unserialize($result->log);
	            $user = JFactory::getUser();
	            $user = "u".$user->id;
	            if( isset($log->{$user}) ){	                
	                if( $log->{$user} >= $resultCoupon->member_coupon_usage_count ){
	                   JError::raiseWarning(1, JText::_("You cannot use this code more than ".$resultCoupon->member_coupon_usage_count." time(s)"));
	                   return false;
	                }
	            }
	        }
	        
	        // Get discount
	        $discount_amount = 0;
	        //if( JRequest::getVar("layout", "") == "credit_confirm" ){
	            if( $resultCoupon->discount_type == "%" ){
	               $discount_amount = ( ($item->price * $resultCoupon->discount)/100 );	               
	            }else{
	               $discount_amount = $resultCoupon->discount;	               
	            }
	        //}
	        
	        $result->discount_amount = $discount_amount;
	        $result->Coupon = $resultCoupon;
	        
	        return $result;
	    }
	    
	    return false;
	}
	
	// Check TAX...
	function checkTAX($item){
		global $jbconfig;
		$db =& JFactory::getDBO();
		$user = JFactory::getUser();
		
		if(isset($jbconfig['tax']) && $item->enable_tax){
			if( $jbconfig['tax']->get("tax_mode", "") != "" ){
				if($jbconfig['tax']->get("tax_mode", "") == "global"){
					// Global tax setting
					if( $jbconfig['tax']->get("global_value", "") != "" ){
						$item->tax_rate = $jbconfig['tax']->get("global_value");
						$item->price = ( $item->price + (($item->price*$item->tax_rate)/100) );
						return $item;
					}
				}else {
					// Regional Setting
					$sql = "SELECT * FROM #__ja_profiles WHERE user_id = ".$user->id;
					$db->setQuery($sql);
					$proInfo = $db->loadObject();
					if( $proInfo ){
						if( isset($proInfo->location_id) ){
							if(!empty($proInfo->location_id)){
								$arrLocation = explode(",", $proInfo->location_id);
								
								// Get enable regional TAX
								$sql = "SELECT a.* FROM #__ja_tax a INNER JOIN #__ja_location b ON a.location_id = b.id WHERE a.published=1 ORDER BY b.name ASC";
								$db->setQuery($sql);
								$taxInfo = $db->loadObjectList();
								if( $taxInfo ){
									foreach ($taxInfo as $tax){
										if( $this->checkInLocation($arrLocation, $tax->location_id) ){
											$item->tax_rate = $tax->tax_value;
											$item->price = ( $item->price + (($item->price*$item->tax_rate)/100) );
											return $item;
										}
									}
								}
							}
						}
					}
				}
			}
		}
		
		return false;
	}
	
	function checkInLocation($empLocation, $taxLocation){
		$db =& JFactory::getDBO();
		
		foreach ($empLocation as $location){
			if( $location == $taxLocation )
				return true;
			
			$sql = "SELECT * FROM #__ja_location WHERE parent_id=".$taxLocation." AND id=".$location;
			$db->setQuery($sql);
			$result = $db->loadObject();
			if( !$result ){
				$sql = "SELECT * FROM #__ja_location WHERE id=".$location." AND parent_id IN (SELECT id FROM #__ja_location WHERE parent_id=".$taxLocation." ) ";
				$db->setQuery($sql);
				$result = $db->loadObject();
				if($result)
					return true;
			}else return true;
		}
		return false;
	}
}
?>